package com.xxl.job.admin.controller.provider;

import com.xxl.job.admin.controller.annotation.PermissionLimit;
import com.xxl.job.admin.core.model.XxlJobGroup;
import com.xxl.job.admin.core.model.XxlJobInfo;
import com.xxl.job.admin.dao.XxlJobGroupDao;
import com.xxl.job.admin.dao.XxlJobInfoDao;
import com.xxl.job.admin.feign.IJobProdiver;
import com.xxl.job.admin.service.XxlJobService;
import com.xxl.job.core.biz.model.ReturnT;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;

/**
 * xxl-job 服务端rpc接口
 *
 * @Author: pc
 * @CreateDate: 2021/10/21 11:41
 */
@RestController
public class JobProdiver implements IJobProdiver {

	@Resource
	private XxlJobService xxlJobService;

	@Resource
	private XxlJobInfoDao xxlJobInfoDao;

	@Resource
	public XxlJobGroupDao xxlJobGroupDao;

	/**
	 * 新增job任务
	 *
	 * @param jobInfo
	 * @return
	 */
	@PermissionLimit(limit = false)
	@Override
	public ReturnT<String> addJob(XxlJobInfo jobInfo) {
		return xxlJobService.add(jobInfo);
	}

	/**
	 * 获取执行器id
	 *
	 * @param appName
	 * @return
	 */
	@PermissionLimit(limit = false)
	@Override
	public ReturnT<Integer> getGroupIdByAppName(String appName) {
		return new ReturnT<>(xxlJobGroupDao.findIdByAppName(appName));
	}

	/**
	 * 新增执行器
	 *
	 * @param xxlJobGroup
	 * @return
	 */
	@PermissionLimit(limit = false)
	@Override
	public ReturnT<Integer> addJobGroup(XxlJobGroup xxlJobGroup) {
		xxlJobGroup.setUpdateTime(new Date());
		xxlJobGroupDao.save(xxlJobGroup);
		return new ReturnT<>(xxlJobGroup.getId());
	}

	/**
	 * 获取job任务信息
	 *
	 * @param jobId
	 * @return
	 */
	@PermissionLimit(limit = false)
	@Override
	public ReturnT<XxlJobInfo> getJobInfo(int jobId) {
		return new ReturnT<>(xxlJobInfoDao.loadById(jobId));
	}

	/**
	 * 更新job任务
	 *
	 * @param jobInfo
	 * @return
	 */
	@PermissionLimit(limit = false)
	@Override
	public ReturnT<String> updateJob(XxlJobInfo jobInfo) {
		return xxlJobService.update(jobInfo);
	}

	/**
	 * 停止job任务
	 *
	 * @param id
	 * @return
	 */
	@PermissionLimit(limit = false)
	@Override
	public ReturnT<String> pause(int id) {
		return xxlJobService.stop(id);
	}

	/**
	 * 开始job任务
	 *
	 * @param id
	 * @return
	 */
	@PermissionLimit(limit = false)
	@Override
	public ReturnT<String> start(int id) {
		return xxlJobService.start(id);
	}

	/**
	 * 删除job任务
	 *
	 * @param id
	 * @return
	 */
	@PermissionLimit(limit = false)
	@Override
	public ReturnT<String> remove(int id) {
		return xxlJobService.remove(id);
	}
}
